package org.example.common.util;

import com.alibaba.fastjson2.JSONObject;
import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTCreator;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.exceptions.JWTVerificationException;
import com.auth0.jwt.interfaces.DecodedJWT;
import com.auth0.jwt.interfaces.Verification;
import lombok.extern.slf4j.Slf4j;
import org.example.entity.UserInfoEntity;
import org.example.enums.BaseErrorEnums;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;

@Slf4j
public class JwtUtils {


    private static final String key = "tb_keyd";

    private static final Long EXPIRE_TIME = 30 * 24 * 60 * 60 * 1000L;

    public static String createToken(UserInfoEntity userInfoEntity) {
        JWTCreator.Builder builder = JWT.create();
        Map<String, Object> head = new HashMap<>();
        head.put("typ", "JWT");
        head.put("alg", "HS256");

        Date date = new Date();

        Map map = JSONObject.parseObject(JSONObject.toJSONString(userInfoEntity), Map.class);
        return builder.withHeader(head)
                .withClaim("userInfo", map)
                .withIssuedAt(date)
                .withExpiresAt(new Date(date.getTime() + EXPIRE_TIME))
                .sign(Algorithm.HMAC256(key));
    }


    /**
     * 校验token
     *
     * @param token
     * @return
     */
    public static UserInfoEntity checkJWT(String token) {
        Verification require = JWT.require(Algorithm.HMAC256(key));

        Date nowDate = new Date();
        UserInfoEntity userInfo = null;
        try {
            DecodedJWT verify = require.build()
                    .verify(token);
            Date expiresAt = verify.getExpiresAt();
            Map map = verify
                    .getClaim("userInfo")
                    .as(Map.class);
            userInfo = JSONObject.parseObject(JSONObject.toJSONString(map),UserInfoEntity.class);
            if (expiresAt.compareTo(nowDate) < 0) {
                ThrowBaseErrorUtils.throwError(BaseErrorEnums.LOGIN_JWT_EXPRISE);
            }
        } catch (JWTVerificationException e) {
            e.printStackTrace();
            ThrowBaseErrorUtils.throwError(BaseErrorEnums.LOGIN_JWT_EXPRISE);
        }

        return userInfo;

    }

    /**
     * 获取用户信息
     * @return
     */
    public static UserInfoEntity getUserInfo() {
        UserInfoEntity userInfo;
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        log.info("用户信息：{}", authentication.getName());
        userInfo = JSONObject.parseObject(authentication.getName(), UserInfoEntity.class);
        return userInfo;

    }
}
